/**
 * 
 */
package com.android.dwt.data;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.AlertDialog;
import android.app.Application;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

import com.android.dwt.ListItem;
import com.android.dwt.Position;
import com.android.dwt.R;
import com.android.dwt.R.array;
import com.android.dwt.R.drawable;
import com.android.dwt.service.DWTService;
import com.android.dwt.ui.MainAct;
import com.google.android.maps.GeoPoint;

/**
 * @author xlees
 * 
 */
public class GTDApp extends Application {
	
	private final double[] mInitCoordinate = {39.971036, 116.314659};		// location of Beijing
	private final String TAG = "GTDApp";
	
	public static final int INBOX = 0;
	public static final int NEXT_ACTION = 1;
	public static final int AGENDA = 2;
	public static final int WAITTING = 3;
	public static final int MEMO = 4;
//	public static final int REF = 5;
	
	private SQLiteDatabase db = null;
	private DBOpenHelper dbHelper;

	private DBListAdapter dbla;
	private DBTaskAdapter dbta;
	private Cursor listCursor;
	private Cursor taskCursor;

	public ArrayList<Drawable> mIcon;
	public String[] mList;
	private ArrayList<ListItem> listItems;
	public ArrayList<HashMap<String, Object>> lists;
//	private ArrayList<TaskItem> taskItems;
	private ArrayList<String> contexts;
	private ArrayList<String> projects;
	private ArrayList<Position> positions;
	private ArrayList<String> tags;
	private ArrayList<String> sort;
	
	public ArrayList<String> repeat;
	public ArrayList<String> remind;
	public ArrayList<String> prior;
	public HashMap<String, Integer> sortType;
	public GeoPoint mMapCenter;
	public int mZoomLevel = 10;		// default zoom level
	
	public boolean mPosRemind;
	public boolean mRefresh;
	public boolean mFinishAct;

	private SharedPreferences spLists;
	private SharedPreferences spContexts;
	private SharedPreferences spProjects;
	private SharedPreferences spPositions;
	private SharedPreferences spTags;
	private SharedPreferences spSort;

	public static final String strList = "lists";
	public static final String strContext = "ctts";
	public static final String strProject = "prjs";
	public static final String strPosition = "pos";
	public static final String strTag = "tags";
	public static final String strSort = "sort";
	public static final int MODE = MODE_PRIVATE;

	
	public ArrayList<String> getSort() {
		return sort;
	}

	public void open() throws SQLiteException {
		
		db = dbHelper.getWritableDatabase();
	}

	public void close() {
		db.close();
	}

	/*public void updateList() {
		listCursor = dbla.getAllListItems();

		if (listCursor.getCount() == 0) { // initialize lists only when there is
											// no list
			initLists();
			listCursor = dbla.getAllListItems(); // requery cursor
		}

		listItems.clear();
		if (listCursor.moveToFirst()) {
			do {
				String list = listCursor.getString(DBListAdapter.COL_LIST_NAME);
				String note = listCursor.getString(DBListAdapter.COL_LIST_NOTE);
				listItems.add(new ListItem(list, note));
			} while (listCursor.moveToNext());
		}
	}*/

//	public void updateTask() {
//		taskCursor = dbta.getAllTaskItems();
//
//		taskItems.clear();
//		if (taskCursor.moveToFirst()) {
//			do {
//				String task = taskCursor.getString(DBTaskAdapter.COL_TASK_NAME);
//				String note = taskCursor.getString(DBTaskAdapter.COL_TASK_NOTE);
//				String list = taskCursor.getString(DBTaskAdapter.COL_TASK_LIST);
//
//				TaskItem ti = new TaskItem(task, note);
//				ti.setListName(list);
//				taskItems.add(ti);
//			} while (taskCursor.moveToNext());
//		}
//	}

	/*public void initLists() {
		dbla.insertList(new ListItem("收集篮", ""));
		dbla.insertList(new ListItem("下一步行动", ""));
		dbla.insertList(new ListItem("日程", ""));
		dbla.insertList(new ListItem("等待", ""));
		dbla.insertList(new ListItem("备忘录", ""));
//		dbla.insertList(new ListItem("参考资料", ""));
	}*/
	
	private void initList() {
		
		HashMap<String, Object> hm;
		
		hm = new HashMap<String, Object>();
		hm.put("item_icon", R.drawable.inbox_96);
		hm.put("item_name", "收集篮");
		hm.put("item_count", 0);
		lists.add(hm);
		
		hm = new HashMap<String, Object>();
		hm.put("item_icon", R.drawable.next_96);
		hm.put("item_name", "下一步行动");
		hm.put("item_count", 0);
		lists.add(hm);
		
		hm = new HashMap<String, Object>();
		hm.put("item_icon", R.drawable.agenda_96);
		hm.put("item_name", "日程");
		hm.put("item_count", 0);
		lists.add(hm);
		
		hm = new HashMap<String, Object>();
		hm.put("item_icon", R.drawable.waiting_96);
		hm.put("item_name", "等待");
		hm.put("item_count", 0);
		lists.add(hm);
		
		hm = new HashMap<String, Object>();
		hm.put("item_icon", R.drawable.memo_96);
		hm.put("item_name", "备忘录");
		hm.put("item_count", 0);
		lists.add(hm);
	}
	
	@Override
	public void onCreate() {
		
		super.onCreate();

		Log.e(TAG, "onCreate method is called!");

		dbHelper = new DBOpenHelper(this);
		open();

		if (db == null)
			Log.e(TAG, "db is null!!");

		dbla = new DBListAdapter(db);
		dbta = new DBTaskAdapter(db);
		
		mMapCenter = new GeoPoint(
        		(int) (mInitCoordinate[0] * 1E6),
        		(int) (mInitCoordinate[1] * 1E6));

		listCursor = null;
		taskCursor = null;
		listItems = new ArrayList<ListItem>();
//		taskItems = new ArrayList<TaskItem>();
		
		ComponentName cn = this.startService(new Intent(this, DWTService.class));
		if (cn == null) {
			
			Log.e(TAG, "can not start service");
			
		} else {
			
			Log.e(TAG, "service is already running!");
		}
		
//		updateList();
//		updateTask();
		
		mList = getResources().getStringArray(R.array.list);
		
		// list
		lists = new ArrayList<HashMap<String,Object>>();
		spLists = getSharedPreferences(strList, MODE);
		if (spLists.contains("exist")) {
			
			HashMap<String, Object> hm;
			int count = spLists.getInt("count", 0);
			
			for (int i=0; i<count; i++) {
				
				hm = new HashMap<String, Object>();
				
				String listName = spLists.getString("List["+i+"]", null);
				int listCount = spLists.getInt("List_count["+i+"]", -1);
				
				hm.put("item_name", listName);
				hm.put("item_count", listCount);
				
				lists.add(hm);
			}
			
			lists.get(0).put("item_icon", R.drawable.inbox_96);
			lists.get(1).put("item_icon", R.drawable.next_96);
			lists.get(2).put("item_icon", R.drawable.agenda_96);
			lists.get(3).put("item_icon", R.drawable.waiting_96);
			lists.get(4).put("item_icon", R.drawable.memo_96);
			
		} else {
			
			initList();
			
			Editor edit = spLists.edit();
			edit.putBoolean("exist", true);
			edit.putInt("count", lists.size());
			
			for(int i=0; i<lists.size(); i++) {
				
			     edit.putString("List["+i+"]", (String) lists.get(i).get("item_name"));
			     edit.putInt("List_count["+i+"]", (Integer) lists.get(i).get("item_count"));
			}
			
			edit.commit();
		}

		// context
		contexts = new ArrayList<String>();
		spContexts = getSharedPreferences(strContext, MODE);
		if (spContexts.contains("exist")) { // context file exists
			
			int count = spContexts.getInt("count", 0);
			for (int i = 0; i < count; i++) {
				
				String str = spContexts.getString("Context["+i+"]", null);
				contexts.add(str);
			}
			
		} else { // the first time
			
			// default contexts, and "no context" can not be deleted
			contexts.add("未指定");
			contexts.add("电话");
			contexts.add("电脑");
			
			Editor edit = spContexts.edit();
			edit.putBoolean("exist", true);
			edit.putInt("count", contexts.size());
			for(int i=0; i<contexts.size(); i++){
			     edit.putString("Context["+i+"]", contexts.get(i));
			}
			edit.commit();
		}
		
		projects = new ArrayList<String>();
		spProjects = getSharedPreferences(strProject, MODE);
		if (spProjects.contains("exist")) { // context file exists
			int count = spProjects.getInt("count", 0);
			for (int i = 0; i < count; i++) {
				String str = spProjects.getString("Project["+i+"]", null);
				projects.add(str);
			}
		} else { // the first time
			// default projects, and "no context" can not be deleted
			projects.add("未指定");
			
			Editor edit = spProjects.edit();
			edit.putBoolean("exist", true);
			edit.putInt("count", projects.size());
			for(int i=0; i<projects.size(); i++) {
			     edit.putString("Project["+i+"]", projects.get(i));
			}
			edit.commit();
		}
		
		positions = new ArrayList<Position>();
		spPositions = getSharedPreferences(strPosition, MODE);
		if (spPositions.contains("exist")) { // context file exists
			int count = spPositions.getInt("count", -1);
			
			for (int i = 0; i < count; i++) {
				String addr = spPositions.getString("Address["+i+"]", null);
				String place = spPositions.getString("Place["+i+"]", null);
				int latitude = spPositions.getInt("Latitude["+i+"]", -1);
				int longtitude = spPositions.getInt("Longtitude["+i+"]", -1);
				
				positions.add(new Position(addr, place, latitude, longtitude));
			}
			
		} else { // the first time
			// default positions, and "no position" can not be deleted
			positions.add(new Position("", "未指定", -1, -1));
			
			Editor edit = spPositions.edit();
			
			edit.putBoolean("exist", true);
			edit.putInt("count", positions.size());			// value is 1
			
			for(int i=0; i<positions.size(); i++){
			     edit.putString("Address["+i+"]", positions.get(i).getAddress());
			     edit.putString("Place["+i+"]", positions.get(i).getPlace());
			     edit.putInt("Latitude["+i+"]", positions.get(i).getLatitude());
			     edit.putInt("Longtitude["+i+"]", positions.get(i).getLongtitude());
			}
			edit.commit();
		}
		
		// tags
		tags = new ArrayList<String>();
		spTags = getSharedPreferences(strTag, MODE);
		if (spTags.contains("exist")) { // context file exists
			int count = spTags.getInt("count", 0);
			for (int i = 0; i < count; i++) {
				String str = spTags.getString("Tag["+i+"]", null);
				tags.add(str);
			}
		} else { // the first time
//			TAGs.add("无标签");
			
			Editor edit = spTags.edit();
			edit.putBoolean("exist", true);
			edit.putInt("count", tags.size());
			for(int i=0; i<tags.size(); i++){
			     edit.putString("Tag["+i+"]", tags.get(i));
			}
			edit.commit();
		}
		
		// repeat
		repeat = new ArrayList<String>();
		repeat.add(0,"不重复");
		repeat.add(1,"按天");
		repeat.add(2,"按周");
		repeat.add(3,"按工作日");
		repeat.add(4,"按月");
		repeat.add(5,"按年");
		repeat.add(6,"直到");
		
		//remind
		remind = new ArrayList<String>();
		remind.add(0,"任务开始时");
		remind.add(1,"提前10分钟");
		remind.add(2,"提前30分钟");
		remind.add(3,"提前1个小时");
		remind.add(4,"提前2个小时");
		
		//prior
		prior = new ArrayList<String>();
		prior.add(0,"无");
		prior.add(1,"高");
		prior.add(2,"中");
		prior.add(3,"低");
		
		
		// sort
		sort = new ArrayList<String>();
		sort.add(0,"默认");
		sort.add(1,"按情境");
		sort.add(2,"按位置");
		sort.add(3,"按项目");
		sort.add(4,"按优先级");
		
		// sort type, default is time
		sortType = new HashMap<String, Integer>();
		spSort = getSharedPreferences(strSort, MODE);
		if (spSort.contains("exist")) { 	// context file exists
			
			sortType.put("inbox", spSort.getInt("inbox", 0));
			sortType.put("next", spSort.getInt("next", 0));
			sortType.put("agenda", spSort.getInt("agenda", 0));
			sortType.put("waiting", spSort.getInt("waiting", 0));
			sortType.put("memo", spSort.getInt("memo", 0));
			sortType.put("completed", spSort.getInt("completed", 0));
			sortType.put("trash", spSort.getInt("trash", 0));
			
		} else { // the first time
			
			sortType.put("inbox", 0);
			sortType.put("next", 0);
			sortType.put("agenda", 0);
			sortType.put("waiting", 0);
			sortType.put("memo", 0);
			sortType.put("completed", 0);
			sortType.put("trash", 0);
			
			Editor edit = spSort.edit();
			edit.putBoolean("exist", true);
			
			edit.putInt("inbox", 0);
			edit.putInt("next", 0);
			edit.putInt("agenda", 0);
			edit.putInt("waiting", 0);
			edit.putInt("memo", 0);
			edit.putInt("completed", 0);
			edit.putInt("trash", 0);
			
			edit.commit();
		}
		
		SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
		mPosRemind = sp.getBoolean("pos_remind", true);
	}
	
	public SharedPreferences getSpSortType() {
		return spSort;
	}

	public SharedPreferences getSpProjects() {
		return spProjects;
	}

	public void setSpProjects(SharedPreferences spProjects) {
		this.spProjects = spProjects;
	}

	public SharedPreferences getSpPositions() {
		return spPositions;
	}

	public void setSpPositions(SharedPreferences spPositions) {
		this.spPositions = spPositions;
	}

	public SharedPreferences getSpTags() {
		return spTags;
	}

	public void setSpTags(SharedPreferences spTags) {
		this.spTags = spTags;
	}

	public SharedPreferences getSpContexts() {
		return spContexts;
	}

	public void setSpContexts(SharedPreferences spContexts) {
		this.spContexts = spContexts;
	}

	@Override
	public void onTerminate() {
		// TODO Auto-generated method stub
		Log.i(TAG, "onTerminate method is called!");

		// if (db != null)
		// close();
		super.onTerminate();
	}

	public SQLiteDatabase getDb() {
		return db;
	}

	public void setDb(SQLiteDatabase db) {
		this.db = db;
	}

	public DBOpenHelper getDbHelper() {
		return dbHelper;
	}

	public void setDbHelper(DBOpenHelper dbHelper) {
		this.dbHelper = dbHelper;
	}

	public DBListAdapter getDbla() {
		return dbla;
	}

	public void setDbla(DBListAdapter dbla) {
		this.dbla = dbla;
	}

	public DBTaskAdapter getDbta() {
		return dbta;
	}

	public void setDbta(DBTaskAdapter dbta) {
		this.dbta = dbta;
	}

	public Cursor getListCursor() {
		return listCursor;
	}

	public void setListCursor(Cursor listCursor) {
		this.listCursor = listCursor;
	}

	public Cursor getTaskCursor() {
		return taskCursor;
	}

	public void setTaskCursor(Cursor taskCursor) {
		this.taskCursor = taskCursor;
	}

	public ArrayList<ListItem> getListItems() {
		return listItems;
	}

	public void setListItems(ArrayList<ListItem> listItems) {
		this.listItems = listItems;
	}

	/*public ArrayList<TaskItem> getTaskItems() {
		return taskItems;
	}

	public void setTaskItems(ArrayList<TaskItem> taskItems) {
		this.taskItems = taskItems;
	}*/

	public ArrayList<String> getProjects() {
		return projects;
	}

	public void setProjects(ArrayList<String> projects) {
		this.projects = projects;
	}

	public ArrayList<String> getContexts() {
		return contexts;
	}

	public void setContexts(ArrayList<String> contexts) {
		this.contexts = contexts;
	}

	public ArrayList<Position> getPositions() {
		
		return positions;
	}

	public void setPositions(ArrayList<Position> positions) {
		this.positions = positions;
	}

	public ArrayList<String> getTags() {
		return tags;
	}

	public void setTags(ArrayList<String> tags) {
		this.tags = tags;
	}

}
